# -*- coding: UTF-8 -*-
# Author: Damon(wuud1)
# CreateDate: 
# Message:  cars_part_num 从原表里获取model,remark字段

from MysqlTools import MysqlTools
import json

class Tools:

    def __init__(self, **kwargs):
        self.db = MysqlTools(db_config=kwargs.get("db_config"), type='dict', auto_commit=10000)
        self.src_table = kwargs.get("src_table")
        self.dest_table = kwargs.get("dest_table")

    def get_years(self, yl):
        l = []
        for i in yl:
            for j in i:
                l.append(j)
        min_y = min(l)
        max_y = max(l)
        return '{}-{}'.format(min_y, max_y if max_y != 99999999 else '')

    def run(self):
        sql = '''select * from {}'''.format(self.src_table)
        src_data = self.db.select_all(sql)
        for data in src_data:
            filter_info = json.loads(data.get("extra_info")).get("filter")
            years_list = [i.get("years") for i in filter_info]
            code_list = [i.get("filter_code") for i in filter_info]
            code_l = []
            for i in code_list:
                if isinstance(i, list):
                    for j in i:
                        for k in j.split("."):
                            code_l.append(k)
                else:
                    for j in i.split("."):
                        code_l.append(j)
            model = '.'.join(set(code_l))
            years_l = [[int(j) if j else 99999999 for j in i.split("-")] for i in years_list]
            # for i in years_list:
            #     yl = [j for j in i.split("-") if j]
            years = self.get_years(years_l)
            data['remark'] = years
            data['model'] = model
            data['updatetime'] = 'now()'
            data['createtime'] = 'now()'
            insert_sql = self.db.get_insert_sql(self.dest_table, data)
            self.db.execute_sql(insert_sql)
        self.db.commit_sql()


if __name__ == '__main__':
    db_config = dict(
        host="127.0.0.1",
        port=3306,
        user="root",
        passwd="123456",
        db="nissan_new",
        charset="utf8",
    )
    src_table = 'cars_part_num_old'
    dest_table = 'cars_part_num'
    tools = Tools(db_config=db_config, src_table=src_table, dest_table=dest_table)
    tools.run()